Here is an example of generating PDF in CodeIgniter 4 using TCPDF.

             PDFs are widely used for creating invoices, receipts, reports, and other documents. By reading this guide, you'll learn how to integrate TCPDF in CodeIgniter 4 and incorporate it as a feature in your projects.

CodeIgniter 4 TCPDF : Generate PDF Files in CodeIgniter 4

Table Of Content

1 Prerequisites

1.) PHP version of 8.2
2.) Composer
3.) Mysql

2 Introduction

This tutorial covers generating PDF in CodeIgniter 4 using the TCPDF library. While CodeIgniter lacks a built-in package for PDFs, TCPDF is a popular choice, offering extensive documentation. This guide will show how to integrate TCPDF in CodeIgniter 4.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

To get started, ensure that you have Composer installed on your computer.
Use the following command to install a new CodeIgniter project:

composer create-project codeigniter4/appstarter ci-4-pdf-app

Then, navigate to your project directory:

cd ci-4-pdf-app

3.2 Configure Environment and MySql Database

Rename the env file to .env and set the development mode in the .env file also configure mysql:

# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ci4_pdf
DB_USERNAME=root
DB_PASSWORD=

4 Install the TCPDF Library

To install TCPDF in Codeigniter 4, we can directly use composer.
Run the following command.

composer require tecnickcom/tcpdf

Once it is finished, to use it we can directly call it using the use statement in

use TCPDF;

5 Create A Model and Migration

Set up a migration for the Order table and a model to manage the data.

php spark make:model OrderModel

Edit app/Models/OrderModel.php to configure fields for managing order data.

<?php
namespace App\Models;

use CodeIgniter\Model;

class OrderModel extends Model
{
    protected $table = 'orders';
    protected $primaryKey = 'id';
    protected $allowedFields = ['order_ref','order_invoice','customer_first_name','customer_last_name','customer_address','customer_company','amount','order_status','order_at'];
}

Create a migration file for the orders table:

php spark make:migration AddOrder

Edit the migration file to define the table structure:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddOrder extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'order_ref' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
           'order_invoice' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'customer_first_name' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'customer_last_name' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'customer_address' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'customer_company' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'amount' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'order_status' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'order_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('orders');
    }

    public function down()
    {
        $this->forge->dropTable('orders');
    }
}


Set up a migration for the Order Items table and a model to manage the data.

php spark make:model OrderitemModel

Edit app/Models/OrderitemModel.php to configure fields for managing order data.

<?php
namespace App\Models;

use CodeIgniter\Model;

class OrderitemModel extends Model
{
    protected $table = 'orderitems';
    protected $primaryKey = 'id';
    protected $allowedFields = ['order_id','product_name','item_price','quantity'];
}

Create a migration file for the order items table:

php spark make:migration AddOrderItems

Edit the migration file to define the table structure:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddOrderItems extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'order_id' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
           'product_name' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'item_price' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'quantity' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
         ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('orderitems');
    }

    public function down()
    {
        $this->forge->dropTable('orderitems');
    }
}


Run the migration:

php spark migrate

6 Create New Controller (InvoiceController)

Generate a InvoiceController to handle Generate PDF methods:

php spark make:controller InvoiceController

Add methods for generating PDF:

<?php
namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\OrderModel;
use App\Models\OrderitemModel;
use TCPDF;



class InvoiceController extends BaseController
{
    public function __construct()
    {
        $this->ordermodel = new OrderModel();
        $this->orderitemmodel = new OrderitemModel();
       
    }

    public function index()
    {
        $ordermodel = new OrderModel();
        $data = [
                    'orders' => $this->ordermodel->findAll(),
                ];
        return view('index',$data);
    }

    public function invoice($id)
    {

        $data = [
            'order' => $this->ordermodel->find($id),
            'orderitems' => $this->orderitemmodel->where("order_id",$id)->findAll(),
        ];

        $html = view('invoice',$data);

		$pdf = new TCPDF('L', PDF_UNIT, 'A5', true, 'UTF-8', false);

		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Get Sample Code');
		$pdf->SetTitle('Invoice');
		$pdf->SetSubject('Invoice');

		$pdf->setPrintHeader(false);
		$pdf->setPrintFooter(false);

		$pdf->addPage();

		// output the HTML content
		$pdf->writeHTML($html, true, false, true, false, '');
		//line ini penting
		$this->response->setContentType('application/pdf');
		//Close and output PDF document
		$pdf->Output('invoice.pdf', 'I');
		
    }
}
?>

7 Create View Files

Create an index.php file in app/Views to display the Order data.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DataTables with CodeIgniter 4</title>
     <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.4/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap5.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>Order List</h1>
        <table id="orderTable" class="table table-bordered ">
            <thead>
            <tr>
                    <th scope="col">Order Ref</th>
                    <th scope="col" class="text-right">Amount</th>
                    <th scope="col" class="text-right">Order Status</th>
                    <th scope="col" class="text-right">Download Invoice</th>
                </tr>
            </thead>
            <tbody>
                <?php
                foreach($orders as $order)
                {?>
            <tr>
                    <td><?php echo $order['order_ref'];?></td>
                    <td><?php echo $order['amount'];?></td>
                    <td><?php echo $order['order_status'];?></td>
                    <td>
                    <a target="_blank"
                        title="Generate Invoice"
                        href="invoicepdf/<?php echo $order['id'];?>">
                        <?php echo $order['order_invoice'];?>
                </a>
                    </td>
                </tr>
                <?php
                }?>
            </tbody>
        </table>
    </div>

    <script>
        $(document).ready(function() {
            $('#orderTable').DataTable({});
        });
    </script>
</body>
</html>

Create an invoice.php file in app/Views to Generate Invoice PDF.
    
    <html>
	<head>
		<title>Get Sample Code Codigniter 4 TCPDF Generation
	</head>
	<body>
		<div style="font-size:24px; color:'#dddddd' "><i>Invoice</i></div>
        <hr>
		<table style="line-height: 1.5;" border="0">
            <tr>
                <td><b>Invoice:</b> #<?php echo $order["order_invoice"]; ?></td>
                <td style="text-align:right;"><b>Receiver:</b></td>
            </tr>
            <tr>
                <td><b>Date:</b> <?php echo date('Y-m-d',strtotime($order["order_at"])); ?></td>
                <td style="text-align:right;"><?php echo $order["customer_first_name"] . ' ' . $order["customer_last_name"]; ?></td>
            </tr>
            <tr>
                <td><b>Payment Due:</b><?php echo date('Y-m-d',strtotime($order["order_at"].' + 10 days')); ?></td>
                 <td style="text-align:right;"><?php echo $order["customer_company"]; ?></td>
            </tr>
            <tr>
            <td></td>
            <td style="text-align:right;"><?php echo $order["customer_address"]; ?></td>
            </tr>
        </table>
		<hr>
		
        <div style="border-bottom:1px solid #000;">
        <table style="line-height: 2;">
            <tr style="font-weight: bold;border:1px solid #cccccc;background-color:#f2f2f2;">
                <td style="border:1px solid #cccccc;width:200px;">Item Description</td>
                <td style = "text-align:right;border:1px solid #cccccc;width:85px">Price ($)</td>
                <td style = "text-align:right;border:1px solid #cccccc;width:75px;">Quantity</td>
                <td style = "text-align:right;border:1px solid #cccccc;">Subtotal ($)</td>
            </tr>
<?php
$total = 0;
foreach($orderitems as $item)
{
    $price = $item["item_price"] * $item["quantity"];
    $total += $price;
    ?>
    <tr> <td style="border:1px solid #cccccc;"><?php echo $item["product_name"]; ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($item["item_price"], 2); ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo $item["quantity"]; ?></td>
                    <td style = "text-align:right; border:1px solid #cccccc;"><?php echo number_format($price, 2); ?></td>
               </tr>
<?php
}
?>
<tr style = "font-weight: bold;">
    <td></td><td></td>
    <td style = "text-align:right;">Total ($)</td>
    <td style = "text-align:right;"><?php echo number_format($total, 2); ?></td>
</tr>
</table></div>
	</body>
</html>
    

8 Define a Route

Configure routes in app/Config/Routes.php:

use CodeIgniter\Router\RouteCollection;
$routes->get('/', 'Home::index');
$routes->get('/orders', 'InvoiceController::index');
$routes->get('/invoicepdf/(:any)', 'InvoiceController::invoice/$1');

9 Folder Structure

10 Run Web Server to Test the App

Start the server:

php spark serve

Visit the URL http://localhost:8080/index.php/orders

11 Conclusion

With this example, you now know how to integrate TCPDF in CodeIgniter 4 for generating PDF files.

Reference URL

Tags